if(typeof (tio) == "undefined"){
    tio = {};
}
tio.ws = {};
tio.ws = function ($, layim) {
    this.heartbeatTimeout = 5000;//心跳超时时间，单位：毫秒
    this.heartbeatSendInterval = this.heartbeatTimeout / 2;
    var self = this;

    this.connect = function () {//建立连接
        var url ="ws://localhost:9326?userId="+self.mine.id;//这个ws地址，上线一定要改具体ip
        var socket = new WebSocket(url);
        self.socket = socket;

        socket.onopen = function () {
            console.log("tio ws 启动~");

            self.lastInteractionTime(new Date().getTime());//初始化最后时间
            self.ping();//建立心跳
        };
        socket.onclose = function () {
            console.log("tio ws 关闭~");
            self.reconn();//尝试重连
        };
        socket.onmessage = function (res) {
            console.log("tio ws 接收到消息了！~");
            console.log(res);

            // res = JSON.parse(res.data);
            res = eval('('+res.data+')');
            if(res.emit === 'chatMessage'){
                layim.getMessage(res.data); //res.data即你发送消息传递的数据（阅读：监听发送的消息）
            }

            self.lastInteractionTime(new Date().getTime());//更新最后时间
        };
        socket.onerror = function (res) {
            console.log("tio ws 发生错误了！~");
            console.log(res);
        };
    };
    
    this.openChatWindow = function () {//获取个人信息，并打开窗口
        $.ajax({// 获取个人、群聊信息
            url: "/chat/getMineAndGroupInfo",
            async: false,//设置为同步
            success: function (res) {
                self.group = res.data.group;
                self.mine = res.data.mine;
            }
        });

        var cache =  layui.layim.cache();
        cache.mine = self.mine;

        layim.chat(self.group); // 打开窗口

        layim.setChatMin(); //收缩聊天面板
    };

    this.sendChatMessage = function () {//发送聊天消息
        layim.on('sendMessage', function(res){
            self.socket.send(JSON.stringify({
                type: 'chatMessage' //随便定义，用于在服务端区分消息类型
                ,data: res
            }));
        });
    };

    this.initHistoryMessage = function () {//初始化历史聊天记录并回显
        localStorage.clear();
        $.ajax({
            url: '/chat/getGroupHistoryMsg',
            success: function (res) {
                var data = res.data;
                if(data.length < 1){
                    return;
                }

                for (var i in data){
                    layim.getMessage(data[i]);
                }
            }
        });
    };

    // 心跳相关~
    this.lastInteractionTime = function () {
        if(arguments.length == 1){
            this.lastInteractionTimeValue = arguments[0];
        }

        return this.lastInteractionTimeValue;
    };

    this.ping = function () {
        console.log("---------> 准备心跳ing~");

        self.pingIntervalId = setInterval(function () {//建立一个定时器，定时心跳
            var iv = new Date().getTime() - self.lastInteractionTime();//已经多久没发消息了

            //debugger

            if((self.heartbeatSendInterval + iv) >= self.heartbeatTimeout){//单位：秒
                self.socket.send(JSON.stringify({
                    type: 'pingMessage'
                    ,data: 'ping'
                }));

                console.log("---------> 心跳ing~");
            }
        },self.heartbeatSendInterval)
    };

    this.reconn = function () {
        //先删除心跳定时器
        clearInterval(self.pingIntervalId);

        //然后尝试重连
        self.connect();
    }
};